<script setup lang="ts">
	import { ref, reactive, unref, computed } from 'vue'
	import { onLoad, onShow } from '@dcloudio/uni-app'
	import { route } from '@/uni_modules/uview-plus'
	import { useNotify } from '@/hooks/web/useNotify/index.js'
	import { useLocation } from '@/hooks/web/useLocation'
	import { orderReturn, shopEdit } from '@/package_tms/api/Home'

	// 消息弹窗
	const NotifyRef = ref<any>(null)
	const { showNotify } = useNotify(NotifyRef)

	const money = ref(0)
	const remark = ref('')

	interface RouteParams {
		id : string,
		name : string,
		order_amount : string,
		store_id : string,
		order_status : string,
		yc_money : string,
		detail : Array
	}
	const routeParams = ref<RouteParams>({
		id: '',
		name: '',
		order_amount: '',
		store_id: '',
		order_status: '',
		yc_money: '',
		detail: []
	})
	onLoad((options) => {
		routeParams.value = options as RouteParams
		routeParams.value.detail = JSON.parse(routeParams.value.detail).map((item) => {
			return {
				...item,
				delivery_num: item.num
			}
		})
	})

	// 使用computed计算总和
	const totalQuantity = computed(() => {
		return routeParams.value.detail.reduce((accumulator, currentItem) => {
			return accumulator + parseFloat(currentItem.real_price) * currentItem.delivery_num
		}, 0).toFixed(2)
	});

	const totalQuantityAll = computed(() => {
		const result = Number(totalQuantity.value) - Number(routeParams.value.yc_money)
		return result < 0 ? 0 : result.toFixed(2);
	});

	const useUploadImg = () => {
		const fileList1 = ref<any[]>([])

		// 添加图片
		type UploadImageFile = {
			size : number,
			type : 'image',
			url : string,
			thumb : string
		}
		type UploadImageParams = {
			file : UploadImageFile | UploadImageFile[],
			index : number,
			name : string
		}
		type AddImage = (event : UploadImageParams) => any
		// 新增图片
		const addImage = async (event) => {
			// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
			let lists = [].concat(event.file);
			let fileListLen = fileList1.value.length;
			lists.map((item) => {
				fileList1.value.push({
					...item,
					status: 'uploading',
					message: '上传中',
				});
			});
			for (let i = 0; i < lists.length; i++) {
				const result = await uploadImage(lists[i].url);
				let item = fileList1.value[fileListLen];
				fileList1.value.splice(fileListLen, 1, {
					...item,
					status: 'success',
					message: '',
					url: result,
				});
				fileListLen++;
			}
		};

		const uploadImage = (url) => {
			return new Promise((resolve, reject) => {
				let a = uni.uploadFile({
					url: `${process.env.VUE_APP_BASE_URL}/driver/task/upload`,
					filePath: url,
					name: 'file',
					header: {
						'content-type': 'application/json;charset=utf-8',
						'token': uni.getStorageSync('trioToken'),
					},
					success: (res) => {
						const data = JSON.parse(res.data)
						if (data.code !== 200) {
							uni.showToast({
								title: `${data.msg},请重新上传!`,
								icon: 'none'
							})
							return
						}
						setTimeout(() => {
							resolve(data.data.url);
						}, 1000);
					},
				});
			});
		};
		// 删除图片
		const delImage = (event : UploadImageParams) => {
			fileList1.value.splice(event.index, 1)
		}

		return {
			fileList1,
			addImage,
			delImage,
			uploadImage
		}
	}

	const { fileList1, addImage, delImage, uploadImage } = useUploadImg()

	const validatePositiveInteger = (event, val) => {
		const inputVal = event
		const delivery_num = parseInt(inputVal, 10);
		if (delivery_num < 0 || isNaN(delivery_num)) {
			// 如果输入为空、不是正数或不是数字，则重置
			val.delivery_num = val.num
			showNotify({
				type: 'error',
				message: '数量必须为正数！'
			});
		} else if (Number(inputVal) > Number(val.num)) {
			val.delivery_num = val.num
			showNotify({
				type: 'error',
				message: '不可以大于订单数量！'
			});
		} else {
			// 如果输入是正整数，则更新数值
			val.delivery_num = String(delivery_num);
		}
	}

	const validatePositive = () => {
		// 检查输入是否为有效数字
		if (isNaN(Number(money.value))) {
			showNotify({
				type: 'error',
				message: '请输入有效的数字金额！'
			});
			return false;
		}
		// 检查金额是否为正数
		if (Number(money.value) < 0) {
			showNotify({
				type: 'error',
				message: '金额必须为正数！'
			});
			return false;
		}
		// 检查金额是否大于订单金额
		if (Number(money.value) > Number(totalQuantity.value)) {
			showNotify({
				type: 'error',
				message: '不可以大于订单金额！'
			});
			return false;
		}
	}

	const submitLoading = ref(false)
	const { getLocation } = useLocation()
	const submit = async () => {
		// 图片
		if (fileList1.value.length == 0) {
			showNotify({
				type: 'error',
				message: '请上传图片！'
			});
			return false;
		}
		submitLoading.value = true
		try {
			const location = await getLocation()
			const dataAll = routeParams.value.detail.map((item) => {
				return {
					// item_id: item.id,
					dealer_goods_id: item.goods_id,
					// dealer_goods_spec_id: item.goods_spec_id,
					transfer_num: Number(item.delivery_num)
				}
			})
			const params = {
				order_id: unref(routeParams).id,
				image: fileList1.value.map((item) => item.url).join(','),
				remark: remark.value,
				lat: location.latitude,
				lon: location.longitude,
				detail: JSON.stringify(dataAll)
			}
			const res = await orderReturn(params)
			showNotify({
				type: 'success',
				message: res.msg
			})
			setTimeout(() => {
				route({
					type: 'redirect',
					url: 'package_tms/pages/Detail/index',
					params: {
						store_id: routeParams.value.store_id,
						store: routeParams.value.name,
						order_status: routeParams.value.order_status
					}
				})
			}, 1000)
		} catch (err) {
			showNotify({
				type: 'error',
				message: err.msg
			})
		} finally {
			submitLoading.value = false
		}
	}

	const position = () => {
		uni.chooseLocation({
			success: (res) => {
				if (res.errMsg === 'chooseLocation:ok') {
					xiuLat(res.latitude, res.longitude)
				}
			}
		})
	}
	// 修改经纬度
	const xiuLat = async (lat, lon) => {
		try {
			const params = {
				id: routeParams.value.store_id,
				lat,
				lon
			}
			const res = await shopEdit(params)
			showNotify({
				type: 'success',
				message: res.msg
			})
		} catch (err) {
			showNotify({
				type: 'error',
				message: err.msg
			})
		}
	}
</script>
<template>
	<view class="content">
		<view class="content-box" style="display: flex;justify-content: space-between;">
			<view class="content-name">客户名称：<span
					style="color: rgba(2, 14, 36, 1);font-size: 28rpx;">{{routeParams.name}}</span></view>
			<view class="content-text" @click="position">位置校准</view>
		</view>
		<view class="content-list">
			<up-row justify="space-between">
				<up-col span="6">
					<up-text text="商品名称" size="12" color="rgba(100, 101, 102, 1)" align="left"></up-text>
				</up-col>
				<up-col span="2">
					<up-text text="单价" size="12" color="rgba(100, 101, 102, 1)" align="left"></up-text>
				</up-col>
				<up-col span="2">
					<up-text text="订单数" size="12" color="rgba(100, 101, 102, 1)" align="left"></up-text>
				</up-col>
				<up-col span="2">
					<up-text text="签收数" size="12" color="rgba(100, 101, 102, 1)" align="left"></up-text>
				</up-col>
			</up-row>
			<block v-for="(val, ind) in routeParams.detail" :key="ind">
				<up-row justify="space-between">
					<up-col span="6">
						<view style="display: flex;gap: 3rpx;font-weight: 500;">
							<up-tag style="display: flex;gap: 3rpx;font-weight: 500;" text="赠品" plain size="mini"
								v-if="val.goods_type == '2'"></up-tag>
							<up-text :text="val.goods.goods_name" align="left"></up-text>
						</view>
					</up-col>
					<up-col span="2">
						<up-text :text="val.sale_price" color="rgba(101, 103, 105, 1)" align="left"></up-text>
					</up-col>
					<up-col span="2">
						<up-text :text="val.num" color="rgba(101, 103, 105, 1)" align="left"></up-text>
					</up-col>
					<up-col span="2">
						<up-input v-model="val.delivery_num" type="number" placeholder=""
							:customStyle="{backgroundColor: '#f0f0f0'}" border="none"
							@blur="validatePositiveInteger($event, val)"></up-input>
					</up-col>
				</up-row>
			</block>
		</view>
		<view class="content-box">
			<view class="content-name">订单金额：<span
					style="color: rgba(2, 14, 36, 1);font-size: 28rpx;">￥{{Number(routeParams?.order_amount).toFixed(2)}}</span></view>
			<view class="content-name">签收金额：<span
					style="color: rgba(2, 14, 36, 1);font-size: 28rpx;">￥{{Number(totalQuantity).toFixed(2)}}</span></view>
		</view>

		<!-- 备注 -->
		<view class="payment-method">
			<view class="method-header">
				<view class="header-left">备注</view>
			</view>
			<view class="method-foot">
				<up-input placeholder="备注信息" border="surround" v-model="remark"></up-input>
			</view>
		</view>
		<view class="content-foot">
			<view class="foot-name">图片</view>
			<view class="img-list">
				<up-upload :fileList="fileList1" @afterRead="addImage" @delete="delImage" multiple :maxCount="3"
					:previewFullImage="true"></up-upload>
			</view>
		</view>
		<view class="foot-button">
			<up-button text="提交" :loading="submitLoading" :disabled="submitLoading" @click="submit()"
				color="rgba(55, 131, 252, 1)"></up-button>
		</view>
		<up-notify ref="NotifyRef"></up-notify>
	</view>
</template>

<style scoped lang="scss">
	.content {
		width: 100%;
		background: rgba(242, 243, 245, 1);
		padding: 24rpx;
		box-sizing: border-box;

		.content-box {
			width: 702rpx;
			padding: 30rpx;
			border-radius: 13rpx;
			box-sizing: border-box;
			margin-bottom: 20rpx;
			background: rgba(255, 255, 255, 1);

			.content-name {
				font-size: 24rpx;
				color: rgba(100, 101, 102, 1);
			}

			.content-text {
				font-size: 24rpx;
				color: rgba(55, 131, 252, 1);
			}
		}

		.content-list {
			width: 702rpx;
			padding: 30rpx;
			border-radius: 13rpx;
			background: rgba(255, 255, 255, 1);
			display: flex;
			flex-direction: column;
			gap: 20rpx;
			box-sizing: border-box;
			margin-bottom: 20rpx;
		}

		.payment-method {
			width: 702rpx;
			border-radius: 13rpx;
			background: rgba(255, 255, 255, 1);
			margin: 20rpx auto;
			padding: 30rpx;
			box-sizing: border-box;

			.method-header {
				display: flex;
				justify-content: space-between;

				.header-left {
					font-size: 28rpx;
					color: rgba(2, 14, 36, 1);
				}

				.header-right {
					font-size: 24rpx;
					font-weight: 500;
					color: rgba(155, 157, 159, 1);
				}
			}

			.payment-container {
				display: flex;
				justify-content: space-between;
				margin-top: 40rpx;
			}

			.method-foot {
				margin: 20rpx 0rpx;
			}
		}

		.content-foot {
			width: 702rpx;
			border-radius: 12rpx;
			background: rgba(255, 255, 255, 1);
			padding: 30rpx;
			box-sizing: border-box;
			margin: 20rpx auto;

			.foot-name {
				font-size: 28rpx;
				font-weight: 700;
				color: rgba(2, 14, 36, 1);
			}

			.img-list {
				margin-top: 20rpx;
			}

		}

		.foot-button {
			margin-top: 20rpx;
			margin-bottom: 80rpx;
		}

		.payment-method {
			width: 702rpx;
			border-radius: 13rpx;
			background: rgba(255, 255, 255, 1);
			margin: 20rpx auto;
			padding: 30rpx;
			box-sizing: border-box;

			.method-header {
				display: flex;
				justify-content: space-between;

				.header-left {
					font-size: 28rpx;
					color: rgba(2, 14, 36, 1);
				}

				.header-right {
					font-size: 24rpx;
					font-weight: 500;
					color: rgba(106, 107, 107, 1);
				}
			}

			.method-line {
				width: 654rpx;
				height: 2rpx;
				background: rgba(0, 0, 0, 0.1);
				margin: 20rpx 0rpx;
			}

			.method-main {
				display: flex;
				justify-content: space-between;

				.main-name {
					font-size: 28rpx;
					color: rgba(2, 14, 36, 1);
				}

			}

			.method-foot {
				margin: 20rpx 0rpx;
			}
		}
	}
</style>